/**
 * Created by cuppi on 2017/7/31.
 */
let express = require('express');
let router = express.Router();
let path = require('path');
var fs = require('fs');
let NetworkManager = require('../network/NetworkManager');
let RandomManager = require('../util/RandomManager');
var FaceManager = require('../ai/FaceManager');
let CouponDAO = require('../util/CouponDAO');
let StringTool = require('../tool/StringTool');
let UserFaceDAO = require('../util/UserFaceDAO');
const TEST_GROUP = 'TestActivity';

const xScale = 20/3.0;
/* GET users listing. */
router.get('/', function (req, res, next) {
    handleRouter(req, res, next)
});

router.post('/', function (req, res, next) {
    handleRouter(req, res, next)
});

function handleRouter(req, res, next) {
    // http://ojljqad2c.qnssl.com/dae69d11a1e64ca5852fcac37b3e8fde
    let userFaceUrl = req.query.userFaceUrl || 'http://ojljqad2c.qnssl.com/dae69d11a1e64ca5852fcac37b3e8fde';
    if (req.body.userFaceUrl){
        userFaceUrl = req.body.userFaceUrl;
    }
    if (!userFaceUrl){
        res.json({data: {}, errorCode: -1, message: '参数缺失'});
        res.end();
        return;
    }

    var image = fs.readFileSync(path.resolve(__dirname, '../pengdashuai.jpeg'));
    FaceManager.defaultManager().detectUserFromImage(image).then(data => {
        console.log(JSON.stringify(data));
        res.json({data: data, errorCode: 0, message: ''});
        res.end();
    });
    return;
    FaceManager.defaultManager().identifyUserFromUrl(userFaceUrl, TEST_GROUP).then(data => {
        console.log(data);
        let user = firstUserFromResult(data.result);
        if (user){
            let userId = user.uid;
            getCouponByUserId(userId, TEST_GROUP).then(data => {
                res.json({data: Object.assign(data, {isNewUserFace: false}), errorCode: 0, message: ''});
                res.end();
            }, error => {
                res.json({data: null, errorCode: -1, message: error.message});
                res.end();
            });
        } else {
            registerUserAndGetCoupon(StringTool.uuidBase64(), userFaceUrl).then(data => {
                res.json({data: Object.assign(data, {isNewUserFace: true}), errorCode: 0, message: ''});
                res.end();
            }, error => {
                res.json({data: null, errorCode: -1, message: error.message});
                res.end();
            })
        }
    }, error => {
        res.send(error);
    });
}

function firstUserFromResult(result) {
    if (result && result.length > 0){
        let user = result[0];
        let userId = user.uid;
        let score = user.scores[0];
        if (score < 50){
            return null;
        }
        return user;
    }
    return null;
}

function getCouponByUserId(userId, userGroup) {
    return new Promise((resolve, reject) => {
        CouponDAO.getCouponByUserId(userId).then(list => {
            if (list.length > 0){
                let conpon = list[0];
                resolve({couponMoney: conpon.couponMoney, isJoined: true})
            } else {
                let couponMoney = randomCouponMoney();
                CouponDAO.setCoupon({userId, userGroup, couponMoney}).then(result => {
                    resolve({couponMoney, isJoined: false});
                }, error => {
                    reject(error);
                })
            }
        }, error => {
            reject(error);
        });
    })
}

function registerUserAndGetCoupon(userId, userFaceUrl) {
    return new Promise((resolve, reject) => {
        registerUser(userId, TEST_GROUP, '非活动用户添加', userFaceUrl).then(data => {
            console.log('添加用户成功:');
            getCouponByUserId(userId, TEST_GROUP).then(data => {
                resolve(data);
            }, error => {
                reject(error);
            });
        }, error => {
            reject(error);
        });
    })
}

function registerUser(userId, userGroup, userInfo, userFaceUrl) {
    return new Promise((resolve, reject) => {
        FaceManager.defaultManager().registerUserFace(userId, userInfo, userFaceUrl, userGroup).then(data => {
            console.log('百度AI注册用户成功' + JSON.stringify(data));
            UserFaceDAO.addUserFace({userId, userGroup, userFaceUrl}).then(result => {
                console.log('数据库写入用户成功');
                resolve(result);
            }, error => {
                reject(error);
            });
        }, error => {
            reject(error);
        });
    })
}

function randomCouponMoney() {
    // 峰值：0.3989422804014329
    let scaledRandom = RandomManager.standardNormalDistribution(-3, 3)*xScale;
    let absRandom = Math.abs(scaledRandom);
    let integerRandom = parseInt(absRandom);
    return integerRandom;
}

module.exports = router;